import React, { useState, useEffect } from "react";
import { NavBar, Space, Toast, DotLoading } from 'antd-mobile';
import { Tabs, PullRefresh } from 'react-vant'; // 引入 PullRefresh
import { FileOutline, PhonebookOutline, ReceiptOutline, ShopbagOutline, ClockCircleOutline } from 'antd-mobile-icons';
import styles from './Shopping.module.css'; // 使用新的CSS模块
import 'react-vant/lib/index.css'; 
import http from '../utils/http';
import { useNavigate } from "react-router-dom";
import { SearchOutline } from 'antd-mobile-icons';

export default function Shopping() {
  const navigate = useNavigate();
  const [cateList, setCateList] = useState([]);
  const [allList, setAllList] = useState([]);
  const [filteredList, setFilteredList] = useState([]);
  const [isRefreshing, setIsRefreshing] = useState(false); // 下拉刷新状态
  const [isLoading, setIsLoading] = useState(true); // 加载状态

  // 存储商品 ID 并跳转详情页
  const as = (id) => {
    localStorage.setItem('id', id);
    navigate(`/xiangqing`);
  };

  // 获取分类列表
  const getCateList = async () => {
    try {
      const res = await http.get('/cate');
      setCateList(res.data.data);
    } catch (error) {
      console.error('获取类型列表失败:', error);
    }
  };
  useEffect(() => {
    getCateList();
  }, []);

  // 获取商品列表（处理刷新逻辑）
  const getList = async () => {
    setIsLoading(true);
    try {
      const res = await http.get('/products');
      setAllList(res.data.data);
      setFilteredList(res.data.data);
    } catch (error) {
      console.error('获取商品列表失败:', error);
      Toast.show({
        icon: 'fail',
        content: '获取商品列表失败'
      });
    } finally {
      setIsLoading(false);
      setIsRefreshing(false); // 结束刷新状态
      // 延迟提示刷新成功
      if (isRefreshing) {
        setTimeout(() => {
          Toast.show({
            icon: 'success',
            content: '刷新成功'
          });
        }, 500);
      }
    }
  };

  // 初始化加载数据
  useEffect(() => {
    getList();
  }, []);

  // 分类切换处理
  const handleCateClick = (cateId) => {
    if (cateId === 'all') {
      setFilteredList(allList);
    } else {
      const filtered = allList.filter(item => item.cid === cateId);
      setFilteredList(filtered);
    }
  };

  // 搜索处理
  const [searchKeyword, setSearchKeyword] = useState('');
  const handleSearchChange = (e) => {
    const keyword = e.target.value;
    setSearchKeyword(keyword);
    if (keyword === '') {
      setFilteredList(allList);
    } else {
      const filtered = allList.filter(item =>
        item.title.toLowerCase().includes(keyword.toLowerCase())
      );
      setFilteredList(filtered);
    }
  };

  // 下拉刷新回调函数
  const onPullRefresh = () => {
    setIsRefreshing(true); // 开启刷新状态
    getList(); // 重新获取数据
  };

  return (
    <div className={styles.shopContainer}>
      {/* 搜索栏 */}
      <div className={styles.shopbox}>
        {/* <NavBar back={null}>抖音商城</NavBar> */}
        <NavBar back={null}></NavBar>
        <div className={styles.inputWrapper}>
          <input
            placeholder="搜索商品"
            className={styles.seacher}
            onChange={handleSearchChange}
            value={searchKeyword}
            prefix={<SearchOutline />}
          />
        </div>
      </div>

      {/* 功能图标 */}
      <div className={styles.icons}>
        <div className={styles.icon}>
          <FileOutline />
          <p>我的订单</p>
        </div>
        <div className={styles.icon}>
          <PhonebookOutline />
          <p>充值中心</p>
        </div>
        <div className={styles.icon}>
          <ReceiptOutline />
          <p>券红包</p>
        </div>
        <div className={styles.icon}>
          <ShopbagOutline />
          <p>抖音超市</p>
        </div>
        <div className={styles.icon}>
          <ClockCircleOutline />
          <p>小时达</p>
        </div>
      </div>

      {/* 商品列表（包裹下拉刷新组件） */}
      <div className={styles.nav}>
        <PullRefresh refreshing={isRefreshing} onRefresh={onPullRefresh}>
          <Tabs>
            <Tabs.TabPane key="all" title="推荐" onClick={() => handleCateClick('all')}>
              {isLoading ? (
                <div className={styles.loadingState}>
                  <DotLoading color='primary' /> 加载中...
                </div>
              ) : (
                <div className={styles.nav_content}>
                  {filteredList.length === 0 ? (
                    <div className={styles.emptyState}>
                      <p>暂无匹配商品</p>
                    </div>
                  ) : (
                    filteredList.map((item) => (
                      <div key={item._id} className={styles.itemList} onClick={() => as(item._id)}>
                        <img src={item.image} alt={item.title} />
                        <p className={styles.pp1}>
                          {item.title}
                        </p>
                        <p>{item.description}</p>
                        <p>￥{item.price}</p>
                      </div>
                    ))
                  )}
                </div>
              )}
            </Tabs.TabPane>
            {cateList.map(item => (
              <Tabs.TabPane
                key={item._id}
                title={item.name}
                onClick={() => handleCateClick(item._id)}
              >
                {isLoading ? (
                  <div className={styles.loadingState}>
                    <DotLoading color='primary' /> 加载中...
                  </div>
                ) : (
                  <div className={styles.nav_content}>
                    {filteredList.filter(subItem => subItem.cid === item._id).length === 0 ? (
                      <div className={styles.emptyState}>
                        <p>暂无匹配商品</p>
                      </div>
                    ) : (
                      filteredList
                        .filter(subItem => subItem.cid === item._id)
                        .map((subItem, index) => (
                          <div key={index} className={styles.itemList} onClick={() => as(subItem._id)}>
                            <img src={subItem.image} alt={subItem.title} />
                            <p className={styles.pp1}>{subItem.title}</p>
                            <p>{subItem.description}</p>
                            <p>￥{subItem.price}</p>
                          </div>
                        ))
                    )}
                  </div>
                )}
              </Tabs.TabPane>
            ))}
          </Tabs>
        </PullRefresh>
      </div>
    </div>
  );
}